package cn.itcast.bos.web.action;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.data.domain.Page;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected T model;
	
	public T getModel() {
		return model;
	}
	
	//构造器完成子类的实例化
	public BaseAction(){
		//构造子类action的对象,获取继承父类的泛型,然后实例化
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		
		ParameterizedType pt = (ParameterizedType) genericSuperclass;
		
		Class<T> modelClass = (Class<T>) pt.getActualTypeArguments()[0];
		
		try {
			model = modelClass.newInstance();
		} catch (InstantiationException |IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("模型构造失败...");
		} 
	}
	
	protected int page;
	protected int rows;
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	protected String ids;
	public void setIds(String ids) {
		this.ids = ids;
	}

	protected void pushPageDataToValueStack(Page<T> pageDate) {
		//返回客户端数据,需要total和rows
		Map<String,Object> result = new HashMap<String,Object>();
		
		//总记录数
		result.put("total", pageDate.getTotalElements());
		//分页数据
		result.put("rows", pageDate.getContent());
		ServletActionContext.getContext().getValueStack().push(result);
	}
}
